package io.bitmax.library.mvp;

import android.content.Context;
import android.os.Bundle;

import io.bitmax.library.utils.Assert;
import io.bitmax.library.utils.ViewFinder;

/**
 * Created by gongdongyang on 2018/9/18.
 */

public abstract class BaseMVPFragment<P extends BaseFragmentPresenter<V>, V extends IBaseUI> extends BaseCoreFragment {

    private P presenter;

    protected ViewFinder viewFinder;

    protected abstract V getUI();

    protected abstract P createPresenter();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        presenter.onSaveInstanceState(outState);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //会不会导致多个Presenter，从而丢失了自己原有的数据
        if (presenter == null){
            presenter = createPresenter();
        }
        presenter.onAttach(context, this);
    }

    @Override
    protected void executeOnceAfterCreateView() {
        viewFinder = new ViewFinder(getRootView());
        Assert.judge(getActivity() instanceof BaseCoreActivity, "请继承BaseCoreActivity");
        presenter.onUIReady((BaseCoreActivity) getActivity(), getUI());
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        presenter.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        presenter.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        presenter.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        presenter.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        presenter.onDetach();
    }

    public P getPresenter() {
        return presenter;
    }

    public boolean isAlive() {
        return this.isAdded() && ((BaseCoreActivity) getActivity()).isAlive();
    }

}
